<template>
  <div class="flex flex-wrap items-center gap-8px">
    <div v-for="(shop, index) in productShops" :key="shop.id" class="select-box shop-pic">
      <el-tooltip :content="shop.name">
        <div class="relative h-full w-full">
          <el-image :src="shop.logo" class="h-full w-full" />
          <Icon
            v-show="!disabled"
            class="del-icon"
            icon="ep:circle-close-filled"
            @click="handleRemoveShop(index)"
          />
        </div>
      </el-tooltip>
    </div>
    <el-tooltip :content="props.placeholder" v-if="canAdd">
      <div class="select-box" @click="openShopTableSelect">
        <Icon icon="ep:plus" />
      </div>
    </el-tooltip>
  </div>
  <!-- 店铺选择对话框（表格形式） -->
  <ShopTableSelect
    ref="shopTableSelectRef"
    :multiple="limit != 1"
    :placeholder="props.placeholder"
    @change="handleShopSelected"
  />
</template>
<script lang="ts" setup>
import { ShopInfoApi, ShopInfoVO } from '@/api/mall/shop/info'
import ShopTableSelect from '@/views/mall/shop/info/components/ShopTableSelect.vue'
import { propTypes } from '@/utils/propTypes'
import { oneOfType } from 'vue-types'
import { isArray } from '@/utils/is'

defineOptions({ name: 'ShopShowcase' })

const props = defineProps({
  modelValue: oneOfType<undefined | number | Array<number> | string | Array<string>>([
    Number,
    String,
    Array
  ]).isRequired,
  placeholder: propTypes.string.def('请选择店铺'),
  // 限制数量：默认不限制
  limit: propTypes.number.def(Number.MAX_VALUE),
  disabled: propTypes.bool.def(false)
})

// 计算是否可以添加
const canAdd = computed(() => {
  // 情况一：禁用时不可以添加
  if (props.disabled) return false
  // 情况二：未指定限制数量时，可以添加
  if (!props.limit) return true
  // 情况三：检查已添加数量是否小于限制数量
  return productShops.value.length < props.limit
})

// 店铺列表
const productShops = ref<ShopInfoVO[]>([])

watch(
  () => props.modelValue,
  async () => {
    const ids = isArray(props.modelValue)
      ? // 情况一：多选
        props.modelValue
      : // 情况二：单选
        props.modelValue
        ? [props.modelValue]
        : []
    // 不需要返显
    if (ids.length === 0) {
      productShops.value = []
      return
    }
    // 只有店铺发生变化之后，才去查询店铺
    if (
      productShops.value.length === 0 ||
      productShops.value.some((shop) => !ids.includes(shop.id!))
    ) {
      productShops.value = await ShopInfoApi.pickShopInfoSimpleList(ids as string[])
    }
  },
  { immediate: true }
)

/** 店铺表格选择对话框 */
const shopTableSelectRef = ref()
// 打开对话框
const openShopTableSelect = () => {
  shopTableSelectRef.value.open(productShops.value)
}

/**
 * 选择店铺后触发
 *
 * @param shops 选中的店铺列表
 */
const handleShopSelected = (shops: ShopInfoVO | ShopInfoVO[]) => {
  productShops.value = isArray(shops) ? shops : [shops]
  emitShopChange()
}

/**
 * 删除店铺
 *
 * @param index 店铺索引
 */
const handleRemoveShop = (index: number) => {
  productShops.value.splice(index, 1)
  emitShopChange()
}
const emit = defineEmits(['update:modelValue', 'change'])
const emitShopChange = () => {
  if (props.limit === 1) {
    const shop = productShops.value.length > 0 ? productShops.value[0] : null
    emit('update:modelValue', shop?.id || 0)
    emit('change', shop)
  } else {
    emit(
      'update:modelValue',
      productShops.value.map((shop) => shop.id)
    )
    emit('change', productShops.value)
  }
}
</script>

<style lang="scss" scoped>
.shop-pic {
  position: relative;
}

.del-icon {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
}
</style>
